<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/10
 * Time: 12:01
 */

namespace plugin\admin\app\logic\user;


use app\common\lib\Constant;
use app\exception\IndexException;
use app\model\user\UserInviteRelationModel;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\font\FontModel;
use plugin\admin\app\model\reward\RewardPlanModel;
use plugin\admin\app\model\user\UserCommissionPlanModel;
use plugin\admin\app\model\user\UserIncomeFlowModel;
use plugin\admin\app\model\user\UserModel;
use plugin\admin\app\model\user\UserPointFlowModel;
use plugin\admin\app\model\withdraw\UserWithdrawModel;
use support\Db;
use support\Request;
use support\Response;

class UserLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        $this->model = new UserModel();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function select(Request $request): Response
    {
        $callback_param = $request->input('callback_param');
        if($callback_param == 'yes'){
            $request->inputSet('callback_param',['<>','']);
        }
        if($callback_param == 'no'){
            $request->inputSet('callback_param',['=','']);
        }
        $field = $request->input('field');
        if($field==false){
            $request->inputSet('field','created_at');
            $request->inputSet('order','desc');
        }
        $isVip = $request->input('is_vip');
        if($isVip==1){
            $request->inputSet('is_vip',1);
            $request->inputSet('vip_expire_time',['>=',date('Y-m-d 00:00:00')]);
        }

        $request->inputSet('isdel','0');
        return parent::select($request);
    }

    protected function formatNormal($items, $total): Response
    {
        $parentUserMap = $this->getListMapById($this->model,$items,'parentid','user_sn',['field'=>['user_sn','nickname','headimgurl']]);

        $rewardPlanMap = $this->getListMapById(RewardPlanModel::getInstance(),$items,'reward_plan_id','id');

        $commissionMap = $this->getListMapById(UserCommissionPlanModel::getInstance(),$items,'user_sn','user_sn');

        //直推人数
        $where = ['level'=>1,['user_sn','in',array_column($items,'user_sn')]];
        $field = ['user_sn',Db::raw('count(user_sn) user_nums')];
        $inviteOneNumsData = UserInviteRelationModel::getInstance()->getWhere($where)->select($field)->groupBy('user_sn')->get()->toArray();
        $inviteOneNumsMap = array_column($inviteOneNumsData,null,'user_sn');

        //累计收益
        $where = ['type'=>1,['user_sn','in',array_column($items,'user_sn')]];
        $field = ['user_sn',DB::raw('sum(amount) total_income')];
        $incomeData = UserIncomeFlowModel::getInstance()->getWhere($where)->select($field)->groupBy('user_sn')->get()->toArray();
        $incomeMap = array_column($incomeData,null,'user_sn');

        //可提现金额
        $where = [['status','in',[1,2]],['user_sn','in',array_column($items,'user_sn')]];
        $field = ['user_sn',DB::raw('sum(amount) can_withdraw_amount')];
        $canWithdrawData = UserIncomeFlowModel::getInstance()->getWhere($where)->select($field)->groupBy('user_sn')->get()->toArray();
        $canWithdrawMap = array_column($canWithdrawData,null,'user_sn');

        //已提现金额
        $where = [['status','in',[0,1,3,5]],['user_sn','in',array_column($items,'user_sn')]];
        $field = ['user_sn',DB::raw('sum(amount) withdraw_amount')];
        $withdrawData = UserWithdrawModel::getInstance()->getWhere($where)->select($field)->groupBy('user_sn')->get()->toArray();
        $withdrawMap = array_column($withdrawData,null,'user_sn');

        //会员点数
        $where = ['type'=>1,['created_at','>=',date('Y-m-d 00:00:00')],['user_sn','in',array_column($items,'user_sn')]];
        $field = ['user_sn',DB::raw('sum(nums) vip_points')];
        $vipPointData = UserPointFlowModel::getInstance()->getWhere($where)->select($field)->groupBy('user_sn')->get()->toArray();
        $vipPointMap = array_column($vipPointData,null,'user_sn');

        //体验会员点数
        $where = ['type'=>3,['user_sn','in',array_column($items,'user_sn')]];
        $field = ['user_sn',DB::raw('sum(nums) vip_points')];
        $vipPointData = UserPointFlowModel::getInstance()->getWhere($where)->select($field)->groupBy('user_sn')->get()->toArray();
        $vipPointMap2 = array_column($vipPointData,null,'user_sn');

        //永久点数
        $where = ['type'=>2,['user_sn','in',array_column($items,'user_sn')]];
        $field = ['user_sn',DB::raw('sum(nums) buy_points')];
        $buyPointData = UserPointFlowModel::getInstance()->getWhere($where)->select($field)->groupBy('user_sn')->get()->toArray();
        $buyPointMap = array_column($buyPointData,null,'user_sn');

        //默认奖励策略
        $defaultLevelRewardsFirst = RewardPlanModel::getInstance()->find(1);
        foreach($items as &$val){
            $val['can_withdraw_amount'] = isset($canWithdrawMap[$val['user_sn']])?$canWithdrawMap[$val['user_sn']]['can_withdraw_amount']:0;
            $val['withdraw_amount'] = isset($withdrawMap[$val['user_sn']])?$withdrawMap[$val['user_sn']]['withdraw_amount']:0;

            $val['reward_plan_name'] = isset($rewardPlanMap[$val['reward_plan_id']])?$rewardPlanMap[$val['reward_plan_id']]['plan_name']:'默认方案';

            if($val['reward_plan_id']>0 && isset($rewardPlanMap[$val['reward_plan_id']])){
                $levelRewardsFirst = $rewardPlanMap[$val['reward_plan_id']];
            }else{
                $levelRewardsFirst = $defaultLevelRewardsFirst;
            }

            $agentLevel = $this->model->getUserAgentVip($val['user_sn']);
            $userTalentRate = json_decode($levelRewardsFirst['v'.$agentLevel.'_plan_data'],true)['talent_rate'];
            $val['talent_rate'] = $userTalentRate.'%';

            //邀请比例
            $levelData = config('param.vip_level'.$agentLevel);
            $val['income_rate'] = ($levelData['income_rate']??'10').'%';

            $val['invit_user_sn'] = isset($parentUserMap[$val['parentid']]) ? $parentUserMap[$val['parentid']]['user_sn'] : '0';
            $val['invit_user_nickname'] = isset($parentUserMap[$val['parentid']]) ? $parentUserMap[$val['parentid']]['nickname'] : '平台';
            $val['invit_user_headimgurl'] = isset($parentUserMap[$val['parentid']]) ? $parentUserMap[$val['parentid']]['headimgurl'] : '';

            $val['total_income_amount'] = isset($incomeMap[$val['user_sn']])? $incomeMap[$val['user_sn']]['total_income'] : 0;
            $val['can_withdraw_amount'] = isset($canWithdrawMap[$val['user_sn']])? $canWithdrawMap[$val['user_sn']]['can_withdraw_amount'] : 0;
            $val['withdraw_amount'] = isset($withdrawMap[$val['user_sn']])? $withdrawMap[$val['user_sn']]['withdraw_amount'] : 0;

            $val['invit_user_nums'] = isset($inviteOneNumsMap[$val['user_sn']]) ?  $inviteOneNumsMap[$val['user_sn']]['user_nums'] : 0;

            $val['buy_points'] = isset($buyPointMap[$val['user_sn']])?$buyPointMap[$val['user_sn']]['buy_points']:0;
            //是否vip
            $val = $this->checkIsVip($val);
            $val['vip_points'] = 0;
            if($val['is_vip']==2){
                $val['vip_points'] = isset($vipPointMap2[$val['user_sn']])?$vipPointMap2[$val['user_sn']]['vip_points']:0;
            }elseif($val['is_vip']==1){
                $val['vip_points'] = isset($vipPointMap[$val['user_sn']])?$vipPointMap[$val['user_sn']]['vip_points']:0;
            }

            //佣金数据
            $defaultCommission = Constant::COMMISSION_RATE;
            $val['commission_plan'] = isset($commissionMap[$val['user_sn']])?$commissionMap[$val['user_sn']]['commission_plan'] : '';
            $val['commission_plan'] = !empty($val['commission_plan']) ? json_decode($val['commission_plan'], true):[];
            if(!empty($val['commission_plan'])){
                $CommissionRateMap = array_column($val['commission_plan'],null,'promotion_project');
                $CommissionRate = [];
                foreach ($defaultCommission as $comm){
                    if(isset($CommissionRateMap[$comm['promotion_project']])==false){
                        $CommissionRate[] = $comm;
                    }else{
                        $CommissionRate[] = $CommissionRateMap[$comm['promotion_project']];
                    }
                }
                $val['commission_plan'] = $CommissionRate;
            }else{
                $val['commission_plan'] = $defaultCommission;
            }

            $talentRate = [];
            foreach($val['commission_plan'] as $v){
                $talentRate[] = $v['promotion_project'].":".$v['talent_commission_rate'].'%';
            }
            $val['talent_rate'] = implode(', ',$talentRate);
        }
        return parent::formatNormal($items, $total);
    }

    public function insert(Request $request): Response
    {
        return parent::insert($request);
    }


    public function update(Request $request): Response
    {
        $rewardPlanId = $request->input('reward_plan_id');
        $rewardPlanId==false && $request->inputSet('reward_plan_id',0);

//        $talentCommissionRate = $request->input('talent_commission_rate');
//        $directCommissionRate = $request->input('direct_commission_rate');
//        if($talentCommissionRate<70 || $talentCommissionRate>80){
//            throw new IndexException(4020,'达人佣金70-79范围');
//        }
//        if(round($talentCommissionRate+$directCommissionRate)>80){
//            throw new IndexException(4020,'达人佣金+直推佣金不能超过80');
//        }


        return parent::update($request);
    }

    public function doUpdate($id, $data)
    {
        $model = $this->model->find($id);
        foreach ($data as $key => $val) {
            $model->{$key} = $val;
        }
        $model->save();

        if(!empty(\request()->input('commission_plan'))){
            $commissionPlan = \request()->input('commission_plan');
            UserCommissionPlanModel::getInstance()->updateOrInsert(
                [
                   'user_sn'=>$model->user_sn
                ],
                [
                    "commission_plan"=>json_encode($commissionPlan,256)
                ]
            );
        }
    }

    public function delete(Request $request): Response
    {
        return parent::isDelete($request);
    }
}